package com.github.butid.data.config;

import com.github.butid.data.XmlNettyServer;
import com.github.butid.data.netty.springboot.SpringBootNettyProperties;
import com.github.butid.data.netty.springboot.SpringContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created By wangjing.dc@qq.com On 2020/08/18
 **/
@Configuration
@ConditionalOnProperty(prefix = "butnetty.boot", name = "xmlServerPort")
@EnableConfigurationProperties(SpringBootNettyProperties.class)
@Slf4j
public class XmlNettyConfiguration {

    @Autowired
    private SpringBootNettyProperties properties;

    @Bean
    public XmlNettyStarter xmlNettyServer(){
        return new XmlNettyStarter();
    }

    @Bean
    @ConditionalOnMissingBean(SpringContext.class)
    public SpringContext springContext() {
        return new SpringContext();
    }


    /**
     * springboot 启动时自动加载NettyStarter, 启动netty服务器.  value = "enabled",
     */
    private class XmlNettyStarter implements InitializingBean, DisposableBean {
        private XmlNettyServer nettyServer;

        @Override
        public void afterPropertiesSet() throws Exception {
            log.info("---------------------------< Starting The Xml Netty Server >---------------------------------");
            long start = System.currentTimeMillis();

            XmlNettyServer nettyServer = new XmlNettyServer(properties.getXmlServerPort());
            nettyServer.start(properties);

            this.nettyServer = nettyServer;
            log.info("-------------------------< Started The Xml Netty Server in {}s>-------------------------------", (System.currentTimeMillis() - start) / 1000);
        }

        @Override
        public void destroy() throws Exception {
            log.info("Stopping The Xml Netty Server");
            nettyServer.stop();
            log.info("Stopped The Xml Netty Server");
        }

    }

}